var arrayEach = require('./arrayEach')

const optionsDefault = {
  key: 'id',
  children: 'children',
  parentKey: null,
  data: null, //	数据存放属性
  clear: false
};
/**
 * @description 树结构转成数组
 * @param {Array} result 
 * @param {*} parentItem 
 * @param {Array} array 
 * @param {Object} opts 
 */
function unTreeList(result, parentItem, array, opts) {
  var optKey = opts.key
  var optParentKey = opts.parentKey
  var optChildren = opts.children
  var optData = opts.data
  var optClear = opts.clear
  arrayEach(array, function (item) {
    var childList = item[optChildren]
    if (optData) {
      item = item[optData]
    }

    if (optParentKey !== null) item[optParentKey] = parentItem ? parentItem[optKey] : null
    result.push(item)

    if (childList && childList.length > 0) {
      unTreeList(result, item, childList, opts)
    }

    if (optClear) {
      delete item[optChildren]
    }

  })

  return result
}
/**
  * 将一个树结构转成数组列表
  *
  * @param {Array} array 数组
  * @param {Object} options 配置项
  * @return {Array}
  */
function toTreeArray(array, options) {
  return unTreeList([], null, array, Object.assign({}, optionsDefault, options))
}

module.exports = toTreeArray;